import { C20AllListing, Layout, UserSubPageBase } from "@/components";
import { useAuth } from "@/store/authContext";
import {
  getUserWaitList,
  removeFromLineUp,
  useUserInfo,
} from "@/store/userDataContext";
import { apiItemTypeMapping } from "@/utils/apiMapping";
import { View } from "@tarojs/components";
import { useDidShow } from "@tarojs/taro";
import { useEffect, useState } from "react";
import style from "./index.module.scss";

export default function UserWaitingList() {
  const { userInfoState, dispatchUserDataAction } = useUserInfo();
  const { dispatchAuthAction } = useAuth();
  const { userData } = userInfoState;
  const [items, setItems] = useState<Array<any>>([]);

  useDidShow(() => {
    getUserWaitList(dispatchUserDataAction, userData!, {
      query: { limit: process.env.defaultPageSize!, page: 1, type: 0 },
      authDispatch: dispatchAuthAction,
    });
  });

  useEffect(() => {
    if (userData!.waitingList) {
      setItems(userData!.waitingList!);
    }
  }, [userData?.waitingList]);

  const removeUserLineUp = async (id, type, i) => {
    const removed = await removeFromLineUp({
      query: { lineUpId: id },
      authDispatch: dispatchAuthAction,
    });
    if (removed) {
      const newItems = items.filter((ni: any, index: number) => {
        return index !== i;
      });
      setItems(newItems);
    } else {
      return;
    }
  };

  return (
    <Layout>
      {items && (
        <UserSubPageBase
          title="心愿单"
          subTitleDark={`您有${items.length}项候补项目`}
          scrollable
        >
          <View className={style.list}>
            <C20AllListing
              cardType="vertical-list-card-center"
              cardList={items.map((waitingListData: any) => ({
                ...waitingListData,
                id: waitingListData.linupId,
                grayedOut: !waitingListData.status,
                link: `pages/${
                  apiItemTypeMapping[waitingListData.mainType]
                }-detail/index?id=${waitingListData.mainId}`,
                waitingListAvailable: waitingListData.seatsLeft,
              }))}
              removeCallback={removeUserLineUp}
            />
          </View>
        </UserSubPageBase>
      )}
    </Layout>
  );
}
